package com.pdg.mcplugin.payd2mine;

import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;

import com.pdg.mcplugin.common.baseclasses.PluginClientBase;

public class BlockListener extends PluginClientBase<Payd2Mine> implements Listener{

	private static final String FORMAT_BLOCK_INFO = "%s(%d,%d,%d)";
	private static final double AMOUNT_NONE = 0.0;

	public BlockListener(Payd2Mine thePlugin) {
		super(thePlugin);
	}
    @EventHandler
    public void onBlockBreak(BlockBreakEvent event)
    {
        if(event.isCancelled())
            return;
        Location theLocation = event.getBlock().getLocation();
        String theBlockInfo = String.format(FORMAT_BLOCK_INFO, theLocation.getWorld().getName(),theLocation.getBlockX(),theLocation.getBlockY(),theLocation.getBlockZ());
        Long theValue = getPlugin().getDataCache().getValueFromBlockCache(theBlockInfo);
        
    	long theTime = System.currentTimeMillis();
        if(theValue!=null){
        	if(theTime-theValue<getPlugin().getConfigurationManager().getCooldownPeriod()){
        		return;
        	}
        }
        double theAmount = getPlugin().getMaterialTable().getAmount(event.getBlock().getType());
        if(theAmount>0.0){
        	getPlugin().getDataCache().addPlayerPay(event.getPlayer().getName(),theAmount);
        }
    }
    
    @EventHandler
    public void onBlockPlace(BlockPlaceEvent event)
    {
        Location theLocation = event.getBlock().getLocation();
        String theBlockInfo = String.format(FORMAT_BLOCK_INFO, theLocation.getWorld().getName(),theLocation.getBlockX(),theLocation.getBlockY(),theLocation.getBlockZ());
        Long theValue = getPlugin().getDataCache().getValueFromBlockCache(theBlockInfo);
        if(theValue!=null){
        	getPlugin().getDataCache().removeBlockFromCache(theBlockInfo);
        }
        if(getPlugin().getMaterialTable().getAmount(event.getBlock().getType())>AMOUNT_NONE){
            getPlugin().getDataCache().addBlockToCache(theBlockInfo, System.currentTimeMillis());
        }
    }
}
